package com.yanqu.road.server.cmd.activity.sonhai;

import com.yanqu.road.entity.activity.sonhai.data.SonHaiPlotData;
import com.yanqu.road.entity.activity.sonhai.data.SonHaiRegionData;
import com.yanqu.road.entity.activity.sonhai.enums.SonHaiRewardFlagEnum;
import com.yanqu.road.entity.activity.sonhai.enums.SonHaiWinFlagEnum;
import com.yanqu.road.entity.activity.sonhai.param.SonHaiCreatePlotResp;
import com.yanqu.road.entity.activity.sonhai.param.SonHaiRewardResp;
import com.yanqu.road.exception.BusinessException;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.SonHaiProto;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.cmd.CrossUnionCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.activity.sonhai.CrossSonHaiActivity;
import com.yanqu.road.server.manager.activity.sonhai.CrossSonHaiActivityMgr;
import com.yanqu.road.server.manager.activity.sonhai.CrossSonHaiTeam;
import com.yanqu.road.server.manager.activity.sonhai.CrossSonHaiUser;
import com.yanqu.road.server.manager.activity.sonhai.pb.SonHaiActivityPb;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.string.StringUtils;

import java.util.concurrent.TimeUnit;

@Cmd(code = Protocol.C2_SON_HAI_RECEIVE_LOG_REWARD, desc = "山海伏兽-领取日志奖励")
public class CrossSonHaiReceiveLogRewardCmd extends CrossUnionCommand {

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {
        SonHaiProto.SonHaiReceiveLogRewardReqMsg reqMsg = SonHaiProto.SonHaiReceiveLogRewardReqMsg.parseFrom(packet.getBytes());
        SonHaiProto.SonHaiReceiveLogRewardRespMsg.Builder respMsg = SonHaiProto.SonHaiReceiveLogRewardRespMsg.newBuilder();
        CrossSonHaiActivity activity = CrossSonHaiActivityMgr.getActivity(reqMsg.getActivityId(), groupId);
        if (activity == null) {
            respMsg.setRet(GameErrorCode.E_SON_HAI_ACTIVITY_NOT_FOUND);
            MessageHelper.sendPacket(serverId, packet.getPlayerId(), YanQuMessageUtils.buildMessage(Protocol.U_SON_HAI_RECEIVE_LOG_REWARD, respMsg));
            return;
        }
        //领取日志奖励
        try {
            //领取日志奖励
            SonHaiRewardResp rewardResp;
            if (reqMsg.getX() == -1 && reqMsg.getY() == -1) {
                //兽王奖励
                rewardResp = activity.receiveBossWinReward(packet.getPlayerId(), reqMsg.getRegionId());
                //构造PB
                respMsg.setRet(0);
                respMsg.setReward(rewardResp.getReward());
                respMsg.setAddAuraScore(rewardResp.getAddAuraScore());
            } else {
//                //地块奖励
//                rewardResp = activity.receiveWinReward(packet.getPlayerId(), reqMsg.getX(), reqMsg.getY());

                long userId = packet.getPlayerId();
                //通用检测
                activity.commonCheck(true, true);
                //获取玩家
                CrossSonHaiUser user = activity.getUser(userId);
                if (user == null) {
                    throw BusinessException.newException(GameErrorCode.E_SON_HAI_USER_NOT_FOUND);
                }
                //获取队伍
                CrossSonHaiTeam team = activity.getTeam(user.getTeamId());
                if (team == null) {
                    throw BusinessException.newException(GameErrorCode.E_SON_HAI_TEAM_NOT_FOUND);
                }
                try {
                    //加锁-队伍，设置5秒超时
                    if (!team.getLock().tryLock( 5, TimeUnit.SECONDS)) {
                        activity.getLogger().error("山海伏兽-领取镇伏奖励-加锁-队伍-超时：{}, {}, {}", userId, reqMsg.getX(), reqMsg.getY());
                        throw BusinessException.newException(GameErrorCode.E_SON_HAI_REQUEST_TIME_OUT);
                    }
                    //获取区域
                    SonHaiRegionData regionData = team.getRegionMap().get(reqMsg.getRegionId());
                    if (regionData == null) {
                        throw BusinessException.newException(GameErrorCode.E_SON_HAI_REGION_NOT_FOUND);
                    }
                    //获取地块
                    SonHaiPlotData plotData = regionData.getPlotData(reqMsg.getX(), reqMsg.getY());
                    if (plotData == null) {
                        throw new BusinessException(GameErrorCode.E_SON_HAI_PLOT_NOT_FOUND);
                    }
                    //判断地块是否被镇伏
                    if (plotData.getWinFlag() != SonHaiWinFlagEnum.WIN_YES.getType()) {
                        throw BusinessException.newException(GameErrorCode.E_SON_HAI_PLOT_NOT_WIN);
                    }
                    //判断地块是否属于自己
                    if (plotData.getUserId() != userId) {
                        throw BusinessException.newException(GameErrorCode.E_SON_HAI_PLOT_NOT_ME);
                    }
                    //判断地块奖励是否已经领取过
                    if (plotData.getGetRewardFlag() != SonHaiRewardFlagEnum.GET_NOT.getType()) {
                        throw BusinessException.newException(GameErrorCode.E_SON_HAI_REWARD_ALREADY_RECEIVE);
                    }
                    //判断奖励是否存在
                    if (StringUtils.isNullOrEmpty(plotData.getReward())) {
                        throw BusinessException.newException(GameErrorCode.E_SON_HAI_EGG_REWARD_NOT_FOUND);
                    }
                    //领取
                    plotData.setGetRewardFlag(SonHaiRewardFlagEnum.GET_YES.getType());
                    //山海灵气
                    long addAuraScore = plotData.getExtraAuraScore();
                    //增加山海灵气
                    if (addAuraScore > 0) {
                        team.changeAuraScore(user, addAuraScore);
                    }
                    //奖励
                    String reward = plotData.getReward();
                    //构造PB
                    respMsg.setRet(0);
                    respMsg.setReward(reward);
                    respMsg.setAddAuraScore(addAuraScore);
                } catch (InterruptedException e) {
                    activity.getLogger().error("山海伏兽-领取镇伏奖励-tryLock报错：{}", e);
                    throw BusinessException.newException(GameErrorCode.E_SON_HAI_REQUEST_TIME_OUT);
                } finally {
                    team.getLock().unlock();
                }
            }
            MessageHelper.sendPacket(serverId, packet.getPlayerId(), YanQuMessageUtils.buildMessage(Protocol.S_SON_HAI_RECEIVE_LOG_REWARD_FROM_CROSS, respMsg));
        } catch (BusinessException e) {
            respMsg.setRet(e.getCode());
            MessageHelper.sendPacket(serverId, packet.getPlayerId(), YanQuMessageUtils.buildMessage(Protocol.U_SON_HAI_RECEIVE_LOG_REWARD, respMsg));
        }
    }

    @Override
    public void sendData() {

    }
}
